﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

using Library.Bll;

namespace Main.Controllers
{
    public class HomeController : Controller
    {

        string EMAIL_NOTIFY_ADDRESS = ConfigurationManager.AppSettings["EmailNotifyAddress"] != null
            ? ConfigurationManager.AppSettings["EmailNotifyAddress"].ToString() : "hanhuatong@126.com";
        public ActionResult Default()
        {
            string table = "Base_AdvImg";
            string column = "*";
            Dictionary<string, object> d = CommonBLL.GetModel(table, column, 1);

            int smsInterval = ConfigurationManager.AppSettings["smsInterval"] != null
                ? int.Parse(ConfigurationManager.AppSettings["smsInterval"].ToString()) : 120;
            ViewData["smsInterval"] = smsInterval;

            return View(d);
        }
        /*
        public ActionResult Default2()
        {
            string table = "Base_AdvImg";
            string column = "*";
            Dictionary<string, object> d = CommonBLL.GetModel(table, column, 1);

            int smsInterval = ConfigurationManager.AppSettings["smsInterval"] != null
                ? int.Parse(ConfigurationManager.AppSettings["smsInterval"].ToString()) : 120;
            ViewData["smsInterval"] = smsInterval;

            return View(d);
        }
        */

        public ActionResult About()
        {
            return View();
        }
        public ActionResult validate()
        {
            return View();
        }

        public ActionResult Success()
        {
            return View();
        }

        public ActionResult Error()
        {
            return View();
        }

        #region 提交订单后保存
        /*
        [HttpPost]
        public ActionResult CorporationSave(FormCollection fc)
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
            foreach (string k in fc.Keys)
            {
                if (k.IndexOf("t0_") >= 0)
                {
                    d[k.Replace("t0_", "")] = fc[k].Trim();
                }
            }
            if (IsBlack(d["contact_phone"].ToString()) || IsBlack(d["contact_phone2"].ToString()))
            {
                return Content("您的电话号码已进入黑名单，请不要恶意申请。");
            }
            else
            {
                try
                {
                    Dictionary<string, object> dMain = new Dictionary<string, object>();
                    dMain["ip"] = GetClientIP();
                    dMain["status"] = 1;
                    int pid = CommonBLL.Add("Order_Main", dMain);
                    d["pid"] = pid;
                    CommonBLL.Add("Order_Detail_Corporation", d);
                    return RedirectToAction("success");
                }
                catch (Exception e)
                {
                    //log
                    InsLogBll.InsertLog("Order_Detail_Corporation", "CorporationSave", "前台企业订单，e.message=" + e.Message);
                    return RedirectToAction("error");
                }
            }
        }
        */
        [HttpPost]
        public ActionResult OrderSave(FormCollection fc)
        {
            //企业和个体工商户
            string tablePrefix = "t0_", tableName = "Order_Detail_Corporation"
                , keys = "address_province,address_city,address_district,contact_phone,business_type,annual_sales,company_age,loan_amount,loan_period,loan_use";

            //服务端验证用户输入是否合法
            if (fc["t0_typ"] != "1" && fc["t0_typ"] != "2" && fc["t0_typ"] != "3")
            {
                InsLogBll.InsertLog("OrderSave", "提交订单", "用户提交了错误的订单类型：" + fc["t0_typ"]);
                return RedirectToAction("error");
            }

            //类型为个人的保存到个人表
            if (fc["t0_typ"].ToString() == "3")
            {
                tablePrefix = "t1_";
                tableName = "Order_Detail_Personal";
                keys = "person_name,address_province,address_city,address_district,contact_phone,business_type,monthly_income,loan_amount,loan_period,loan_use";
            }

            //构造要提交的Dictionary
            Dictionary<string, object> d = new Dictionary<string, object>();
            foreach (string k in fc.Keys)
            {
                if (k.IndexOf(tablePrefix) >= 0)
                {
                    d[k.Replace(tablePrefix, "")] = fc[k].Trim();
                }
            }
            //服务端验证用户是否有未填的必填项
            foreach (var item in keys.Split(','))
            {
                if (d[item] == null || d[item].ToString().Trim() == "")
                {
                    InsLogBll.InsertLog("OrderSave", "提交订单", "必填项未填：" + item);
                    return RedirectToAction("error");
                }
            }
            if (fc["t0_typ"] == "1")
            {
                if (d["corporation_name"] == null || d["corporation_name"].ToString().Trim() == string.Empty)
                {
                    InsLogBll.InsertLog("OrderSave", "提交订单", "必填项未填：corporation_name");
                    return RedirectToAction("error");
                }
            }
            if (fc["t0_typ"] == "2")
            {
                if (d["corporation_owner"] == null || d["corporation_owner"].ToString().Trim() == string.Empty)
                {
                    InsLogBll.InsertLog("OrderSave", "提交订单", "必填项未填：corporation_owner");
                    return RedirectToAction("error");
                }
            }

            //如果电话号码在黑名单里，进行提示
            if (IsBlack(d["contact_phone"].ToString()) || IsBlack(d["contact_phone2"].ToString()))
            {
                return Content("9");
            }
            else
            {
                try
                {
                    Dictionary<string, object> dMain = new Dictionary<string, object>();
                    dMain["ip"] = GetClientIP();
                    dMain["status"] = 1;
                    int pid = CommonBLL.Add("Order_Main", dMain);
                    d["pid"] = pid;
                    CommonBLL.Add(tableName, d);
                    int notifyMode = (ConfigurationManager.AppSettings["NotifyMode"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["NotifyMode"])) ? 2 : int.Parse(ConfigurationManager.AppSettings["NotifyMode"]);
                    string mailBody = GetMailBody(d);
                    if (notifyMode >= 1)
                    {
                        //订单提交后给客服发送提示邮件
                        string mailTitle = string.Format(@"【瀚华通提醒】有客户提交了一个新的贷款申请订单，请及时处理({0})", DateTime.Now.ToString());
                        HanhuaMicroCredit.BLL.OrderNotice.sendEmail(EMAIL_NOTIFY_ADDRESS, mailBody, mailTitle, null);
                    }
                    if (notifyMode >= 2)
                    {
                        //订单提交后给客服发送提醒短信
                        string mobile = ConfigurationManager.AppSettings["smsNotifyNumber"].ToString().Trim();
                        if (!string.IsNullOrEmpty(mobile))
                        {
                            int status = sdkService.sendSMS(ConfigurationManager.AppSettings["smsKey"].ToString()
                           , ConfigurationManager.AppSettings["smsK"].ToString(), "",
                               mobile.Trim().ToString().Split(new char[] { ',' })
                               , mailBody.Replace("<h2>订单详情如下：</h2>", "瀚华通网站有新订单，详情如下：\n").Replace("<p>", "").Replace("</p>", "\n").Replace("<b>", "").Replace("</b>", ""),
                               "", "GBK", 3, Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssfff")));
                        }
                    }
                    return Content("1");
                }
                catch (Exception e)
                {
                    //log
                    InsLogBll.InsertLog(tableName, tableName + "_Save", "前台订单，e.message=" + e.Message);
                    return RedirectToAction("error");
                }
            }
        }

        Webservice.SDKService sdkService = new global::Main.Webservice.SDKService();
        public bool IsBlack(string phone)
        {
            string sql = string.Format("select count(*) from blacklist where phone='{0}' and isvalid=1", phone.Trim());
            int count = (int)CommonBLL.ExecuteSQL4Scalar(sql);
            if (count > 0)
                return true;
            return false;
        }

        private string GetClientIP()
        {
            string result = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = Request.UserHostAddress;
            }
            return result;
        }

        private string GetMailBody(Dictionary<string, object> d)
        {
            try
            {
                string sql = string.Format(@"select [name] from base_district where id={0};
                            select [name] from base_district where id={1};
                            select [name] from base_district where id={2};
                            select [name] from sys_ibdd where id={3};
                            select [name] from sys_ibdd where id={4};"
                    , d["address_province"], d["address_city"], d["address_district"], d["business_type"], d["loan_use"]);
                System.Data.DataSet ds = CommonBLL.ExecuteSQL4Dataset(sql, null);
                d["address_province"] = ds.Tables[0].Rows[0]["name"];
                d["address_city"] = ds.Tables[1].Rows[0]["name"];
                d["address_district"] = ds.Tables[2].Rows[0]["name"];
                d["business_type"] = ds.Tables[3].Rows[0]["name"];
                d["loan_use"] = ds.Tables[4].Rows[0]["name"];
            }
            catch(Exception e) {
                InsLogBll.InsertLog("生成邮件内容1", "生成邮件内容2", "邮件内容获取省份城市贷款用途查表出错，e.message=" + e.Message);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<h2>订单详情如下：</h2>");
            foreach (string k in d.Keys)
            {
                if (k == "typ")
                    continue;
                if (FieldDic().ContainsKey(k))
                {
                    if (!string.IsNullOrEmpty(d[k].ToString()))
                    {
                        if (k == "monthly_income" || k == "annual_sales" || k == "loan_amount")
                        {
                            sb.AppendFormat("<p><b>{0}</b>: {1}元</p>", FieldDic()[k], d[k]);
                        }
                        else if (k == "company_age")
                        {
                            sb.AppendFormat("<p><b>{0}</b>: {1}年</p>", FieldDic()[k], d[k]);
                        }
                        else if (k == "loan_period")
                        {
                            sb.AppendFormat("<p><b>{0}</b>: {1}月</p>", FieldDic()[k], d[k]);
                        }
                        else
                        {
                            sb.AppendFormat("<p><b>{0}</b>: {1}</p>", FieldDic()[k], d[k]);
                        }
                    }
                }
            }
            sb.Append("<p>请尽快处理！</p>"); 
            return sb.ToString();
        }
        private Dictionary<string, object> FieldDic()
        {
            return new Dictionary<string, object>
            {
                {"typ","订单类型"},
                {"corporation_name", "公司名称"},
                {"corporation_owner","企业主名称"},                
                {"person_name", "姓名"},
                {"address_province","省份"},
                {"address_city","城市"},
                {"address_district","区域"},
                {"address_remark","详细地址"},
                {"business_type","从事行业"},
                {"annual_sales","年销售额"},
                {"monthly_income","税前月收入"},
                {"company_age","经营年限"},
                {"loan_amount","贷款金额"},
                {"loan_period","贷款期限"},
                {"loan_use","贷款用途"},
                {"contact_phone","手机号码"},
                {"contact_phone2","备用号码"}
            };
        }
        #endregion
    }
}
